"ui";
importClass(java.io.File);
importPackage(android.text);
importPackage(android.text.style);
ui.statusBarColor("#FF4FB3FF")
var storage = storages.create("悬浮窗信息");


ui.layout(
  <vertical id="main" margin='0 0 0 0' padding="10 10 10 10" bg="#FF4FB3FF">
    <text id="ua" marginTop='5'singleLine="true" ellipsize="end">ua</text>
    <text id="缓存信息">缓存信息</text>
    <text id="cookie信息" singleLine="true" ellipsize="end" >cookie信息</text>
    <text id="GACK" singleLine="true" ellipsize="end" >GA-CK</text>
    <text color="#ff0000">获取CK，按1→2→重新打开脚本→3→4操作即可</text>
    <text color="#F8F8FF">如需登陆小号，点击清除缓存，然后同上操作</text>
    
    <horizontal  weightSum="4" >
      <button id="京东网站" textSize="{{11}}" layout_weight="1">①登陆京东</button>
      <button id="关闭" textSize="{{11}}" layout_weight="1" textColor='#ff0000'>②关闭</button>
      
      <button id="Fck" textSize="{{11}}"layout_weight="1">③刷新GAck</button> 
      <button id="下一页" textSize="{{11}}" layout_weight="1">复制GA-CK</button>
      

    </horizontal>
    <horizontal >
      <frame layout_weight="1">
      
      <button id="上一页" >CK信息</button>
      </frame>
      <frame layout_weight="1">
      <button id="清除缓存" textColor='#ff0000'>清除缓存</button> 
      
      </frame>
      <frame layout_weight="1">
      <button id="刷新" >刷新</button>
      </frame>
      <frame layout_weight="1">
      <button id="切换UA"color="#ff0000">关闭</button>
      </frame>
    </horizontal>
    <webview id="a" h="*" w="*" />
  </vertical >
);




//http.__okhttp__.muteClient(new OkHttpClient.Builder().cookieJar(new org.autojs.autojs.network.util.WebkitCookieManagerProxy()))
var cookieManager = android.webkit.CookieManager.getInstance();
ui.a.getSettings().setJavaScriptEnabled(true);
var url = "https://m.jd.com/"
// var url = "http://www.fynas.com/ua/view"
var webView = ui.a
webView.getSettings().setUserAgentString(随机UA());
setTimeout(显示手机UA, 1000)
ui.a.loadUrl(url);
var CookieStr = cookieManager.getCookie(url);
var CookieStr1 = cookieManager.getCookie(url);


ui.切换UA.on("click", () => {
  // toastLog('为防止CK失效,只内置了一个UA')
  // var webView = ui.a
  // webView.getSettings().setUserAgentString(随机UA());
  // setTimeout(显示手机UA, 1000)
  ui.finish()
})

function 显示手机UA() {
  threads.start(
    function () {
      ui.run(
        function () {
          var ua = 获取手机ua()
          ui.ua.setText('UA: ' + ua)
        }
      )
    }
  )
}
setInterval(
  () => {
    var ua = 获取手机ua()
    ui.ua.setText('UA: ' + ua)
    var 缓存信息 = 当前缓存()
    ui.缓存信息.setText(缓存信息)
    var cookie信息 = 当前Cookie()
    ui.cookie信息.setText(cookie信息)
    var color = "#ff00ff"
    var color1 = "#00EE00"
    markSearch(ui.ua, "UA", color);
    markSearch(ui.缓存信息, "缓存", color);
    markSearch(ui.cookie信息, "cookie", color);
    markSearch(ui.GACK, "GA-CK", color1);
  }, 2000
)

function 获取手机ua() {
  var webView = ui.a
  var ua = webView.settings.getUserAgentString();
  return ua
}

ui.京东网站.on("click", () => {
  var url = "https://plogin.m.jd.com/login/login?appid=300&returnurl=https%3A%2F%2Fwq.jd.com%2Fpassport%2FLoginRedirect%3Fstate%3D2255460083%26returnurl%3Dhttps%253A%252F%252Fhome.m.jd.com%252FmyJd%252Fnewhome.action%253Fsceneval%253D2%2526ufc%253D%2526&source=wq_passport"
  ui.a.loadUrl(url);
})

ui.Fck.on("click", () => {
    var GACK = 当前GACK()
    ui.GACK.setText(GACK)
})

// ui.上一页.on("click", () => {
//     var text = CookieStr
//     setClip(text);
//     toast("原CK复制成功");
//     log(CookieStr)
// })
ui.上一页.on("click", () => {
//   threads.start(
//       function 更新CK() {
//           var url = "http://172.81.216.252:5678/updateCookie";
//           var username = CookieValue2;
//           var res = http.post(url, {
//               "cookie": username,
//   })
//   var text = CookieValue2
//     setClip(text);
//     toast("GA-CK更新成功");
//   console.log('已成功更新CK')
//   log(text)
//           }
//       )
var text = CookieValue2
    setClip(text);
    toast(text);
    log(text)
    }
)


ui.下一页.on("click", () => {
    var text = CookieValue2
    setClip(text);
    toast("GA-CK复制成功\n"+text);
    log(text)
})
ui.关闭.on("click", () => {
 ui.finish()
})


ui.清除缓存.on("click", () => {
  toastLog('清除缓存')
  log('清除缓存前cookie=')
  log(CookieStr)
  var webView = ui.a
  // 不让用js会白屏
  // webView.getSettings().setJavaScriptEnabled(false);
  var CookieStr = cookieManager.getCookie(url);
  var CookieStr1 = cookieManager.getCookie(url);
  cookieManager.removeSessionCookies(null);
  cookieManager.removeAllCookie();
  cookieManager.flush();
  webView.getSettings().setCacheMode(webView.settings.LOAD_NO_CACHE);
  context.deleteDatabase("WebView.db");
  context.deleteDatabase("WebViewCache.db");
  context.getCacheDir().delete();
  webView.clearCache(true);
  webView.clearFormData();
  webView.setWebChromeClient(null);
  webView.setWebViewClient(null);
  android.webkit.WebStorage.getInstance().deleteAllData(); //清空WebView的localStorage
  webView.clearCache(true);
  CookieStr = cookieManager.getCookie(url);
  CookieStr1 = cookieManager.getCookie(url);
  log('清除缓存后cookie=')
  log(CookieStr)
  log(CookieStr1)
})

ui.刷新.on("click", () => {
  toastLog('刷新')
  ui.run(() => {
    var webView = ui.a
    webView.reload()
    setTimeout(显示手机UA, 1000)

  });
})

function 随机UA() {
  var uaArr = [
	"jdapp;android;8.5.12;9;network/wifi;model/GM1910;addressid/1302541636;aid/ac31e03386ddbec6;oaid/;osVer/28;appBuild/73078;adk/;ads/;pap/JA2015_311210|8.5.12|ANDROID9;osv/9;pv/117.24;jdv/0|kong|t_1000217905_|jingfen|644e9b005c8542c1ac273da7763971d8|1589905791552|1589905794;ref/com.jingdong.app.mall.WebActivity;partner/oppo;apprpd/Home_Main;Mozilla/5.0 (Linux; Android 9; GM1910 Build/PKQ1.190110.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/66.0.3359.126 MQQBrowser/6.2 TBS/044942 Mobile Safari/537.36",
  ]
  // var uaArr=require('./uaArr.js')
  var uasLen = uaArr.length
  var n = 随机数(uasLen)
  var ua = uaArr[n]
  return ua

  function 随机数(max) {
    var r = parseInt(max * Math.random())
    return r
  }
}

function 当前缓存() {
  var file3 = activity.getCacheDir();
  var file3Size = getFolderSize(file3)
  file3Size = conver(file3Size)
  var 当前缓存路径 = '缓存: ' + file3 + ': ' + file3Size
  return 当前缓存路径
}
function 当前Cookie() {
  var CookieStr = cookieManager.getCookie(url);
  CookieStr = 'cookie: ' + CookieStr
  return CookieStr
}

function  当前GACK() {
    var CookieStr1 = cookieManager.getCookie(url);
    var CookieValue = CookieStr.match(/pt_key=.+?;/) + CookieStr.match(/pt_pin=.+?;/);
    CookieValue1 = 'GA-CK: ' + CookieValue
    CookieValue2 =  CookieValue
    return CookieValue1
}


function getFolderSize(path) {
  var file = new File(path)
  var size = 0;
  try {
    var fileList = file.listFiles();
    for (var i = 0; i < fileList.length; i++) {
      if (fileList[i].isDirectory()) {
        size = size + getFolderSize(fileList[i]);
      } else {
        size = size + fileList[i].length();
      }
    }
  } catch (e) {
    log(e)
  }
  return size
}

function conver(limit) {
  var size = "";
  if (limit < 0.1 * 1024) { //如果小于0.1KB转化成B
    size = limit.toFixed(2) + "B";
  } else if (limit < 0.1 * 1024 * 1024) { //如果小于0.1MB转化成KB
    size = (limit / 1024).toFixed(2) + "KB";
  } else if (limit < 0.1 * 1024 * 1024 * 1024) { //如果小于0.1GB转化成MB
    size = (limit / (1024 * 1024)).toFixed(2) + "MB";
  } else { //其他转化成GB
    size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB";
  }
  var sizestr = size + "";
  var len = sizestr.indexOf("\.");
  var dec = sizestr.substr(len + 1, 2);
  if (dec == "00") { //当小数点后为00时 去掉小数部分
    return sizestr.substring(0, len) + sizestr.substr(len + 3, 2);
  }
  return sizestr;
}
//删除指定文件夹下所有文件
//param path 文件夹完整绝对路径
function delAllFile(path) {
  var flag = false;
  var file = new File(path);
  if (!file.exists()) {
    return flag;
  }
  if (!file.isDirectory()) {
    return flag;
  }
  var tempList = file.list();
  var temp = null;
  for (var i = 0; i < tempList.length; i++) {
    if (path.endsWith(File.separator)) {
      temp = new File(path + tempList[i]);
    } else {
      temp = new File(path + File.separator + tempList[i]);
    }
    if (temp.isFile()) {
      temp.delete();
    }
    if (temp.isDirectory()) {
      delAllFile(path + "/" + tempList[i]); //先删除文件夹里面的文件
      files.remove(path + "/" + tempList[i]); //再删除空文件夹
      flag = true;
    }
  }
  return flag;
}

function highlightText(text, start, length, color) {
  if (!(typeof (text) == 'object' && text.getClass().getName() == 'android.text.SpannableStringBuilder')) {
    text = new SpannableStringBuilder(text);
  }
  text.setSpan(new ForegroundColorSpan(colors.parseColor(color)), start, start + length, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  return text;
}

function highlightView(view, start, length, color) {
  view.setText(highlightText(view.text(), start, length, color));
}

function markSearch(view, keywords, color) {
  let textStr = view.text();
  let text = textStr;
  let i = -1;
  while (i < textStr.length - 1) {
    i = textStr.indexOf(keywords, i + 1);
    if (i >= 0) {
      text = highlightText(text, i, keywords.length, color);
    } else {
      break;
    }
  }
  view.setText(text);
  return text;
}
